import 'package:get/get.dart';
import 'package:xindong/common/xindong_common_vm.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/network/xindong_response.dart';
import 'package:xindong/manager/xindong_hello_ctr.dart';
import 'package:xindong/routes/tab_moments/controller/xindong_dongtai_handle.dart';
import 'package:xindong/routes/tab_moments/model/xindong_dongtai_class.dart';

class XinDongDongTaiVM extends XinDongCommonVM {
  static XinDongDongTaiVM get to => Get.find();

  final int type; // 0推荐全部 = 1关注
  final _handle = XinDongDongTaiHandle();

  XinDongDongTaiVM({required this.type});

  void notifyRefresh() {
    if (isLoading == true) {
      return;
    }
    refreshController.requestRefresh(needMove: true, duration: const Duration(milliseconds: 200));
  }

  // 请求加载列表
  void requestLoadData({required int yemian, int yemianSize = 20, required Function(NetworkResponse) callback}) {
    isLoading = true;
    _handle.requestListWithType(
      yemian: yemian,
      yemianSize: yemianSize,
      type: type,
      callback: (result) {
        callback(result);
        Future.delayed(const Duration(milliseconds: 1000)).whenComplete(() => isLoading = false);
      },
    );
  }

  List<XinDongDongTaiClass> jsonToArrayClass(List result) {
    return result.map((e) => XinDongDongTaiClass.fromJson(e)).toList();
  }

  @override
  void refreshData({object}) {
    yemian = 0;
    requestLoadData(
      yemian: 0,
      callback: (object) async {
        if (object.code == XinDongServerStatus.success) {
          final list = jsonToArrayClass(object.result);
          hasMore = list.isNotEmpty;
          dataList = await XinDongHelloCtr.to.matchGreetData(list);
        }
        // 最后调用父类方法，执行后续操作
        super.refreshData(object: object);
      },
    );
  }

  @override
  void loadMoreData({object}) {
    if (!hasMore) {
      refreshController.loadNoData();
      return;
    }
    yemian++;
    requestLoadData(
      yemian: yemian,
      callback: (object) async {
        if (object.code == XinDongServerStatus.success) {
          final list = jsonToArrayClass(object.result);
          hasMore = list.isNotEmpty;
          final tempList = await XinDongHelloCtr.to.matchGreetData(list);
          dataList!.addAll(tempList); // 拼接数据
        } else {
          yemian--;
        }
        // 最后调用父类方法，执行后续操作
        super.loadMoreData(object: object);
      },
    );
  }
}
